<template>
  <el-dialog :title="ruleForm.id ? '编辑角色' : '新增角色'" :visible="showDialog" @close="closeDilog">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="角色名称" prop="title">
        <el-input v-model.trim="ruleForm.title" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model.trim="ruleForm.description" />
      </el-form-item>
      <el-form-item>
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-button @click="closeDilog">取 消</el-button>
            <el-button type="primary" @click="submitRole">确 定</el-button>
          </el-col>

        </el-row>

      </el-form-item>

    </el-form>
  </el-dialog>
</template>

<script>
import { addRoles, getRoles, editRoles } from '@/api/roles'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      ruleForm: {
        title: '',
        description: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      id: ''
    }
  },

  methods: {
    // 关闭弹窗
    closeDilog() {
      this.ruleForm = {}
      this.$emit('update:showDialog', false)
      this.$refs.ruleForm.resetFields() // 重置校验字段
    },
    async submitRole() {
      try {
        await this.$refs.ruleForm.validate()
        if (this.ruleForm.id) {
          await editRoles(this.ruleForm)
        } else {
          await addRoles(this.ruleForm)
        }
        await this.$emit('getRolesList')
        this.closeDilog()
      } catch (error) {
        console.log(error)
      }
    },
    async editRole() {
      const res = await getRoles(this.id)
      this.ruleForm = res
    }
  }

}
</script>

<style>

</style>
